/**
 * field_img
 */
layui.define(['YunjField','jquery','yunj','upload'], function (exports) {

    let YunjField = layui.YunjField;
    let doc = document;
    let $ = layui.jquery;
    let upload = layui.upload;

    class YunjImg extends YunjField {

        constructor(options={}) {
            super(options);
            // 上传操作元素elem
            this.upload_action_elem=`#${this.id} .img-upload-box .upload-action-elem`;
            // 图片预览容器dom元素对象
            this.img_preview_box_el=null;
            // 上传文件
            this.upload_files={};
            // 上传进度定时器
            this.upload_progress_timer=null;
            // 上传进度
            this.upload_progress_rate_num=0;
        }

        defineExtraArgs(){
            let that = this;
            return {
                size:yunj.config("file.upload_img_size"),
                ext:yunj.config("file.upload_img_ext"),
                disabled:false
            };
        }

        layoutControl() {
            let that = this;
            let controlHtml = `<div class="img-upload-box">
                                    <div class="img-select-box" title="${that.args.disabled?'禁用':'选择图片上传'}">
                                        <i class="layui-icon layui-icon-upload"></i>
                                        <span>图片上传</span>
                                    </div>
                                    <i class="upload-action-elem"></i>
                                </div>`;
            return `<div class="layui-input-inline yunj-input-inline">${controlHtml}</div>`;
        }

        // 设置字段简介
        layoutDesc() {
            let that = this;
            return `<div class="yunj-form-item-desc">允许上传大小不超过 ${that.args.size}MB 且格式为 ${that.args.ext} 的文件。${that.args.desc}</div>`;
        }

        renderDoneSetValue(val){
            let that=this;
            $(doc).bind(`yunj_form_${that.formId}_render_done`,function () {
                that.setValue(val);
            });
        }

        setValue(val=''){
            let that=this;
            that.set_img_preview_box_layout(val);
        }

        getValue(){
            let that=this;

            if(!that.img_preview_box_el||that.img_preview_box_el.find('img').length<=0) return '';
            let src=that.img_preview_box_el.find('img').attr('src');
            return !src||!yunj.isString(src)||src.length>2000?'':src;
        }

        set_img_preview_box_layout(src=''){
            let that = this;

            if(src.length<=0){
                if(that.img_preview_box_el) that.img_preview_box_el.remove();
                that.img_preview_box_el=null;
                return false;
            }

            if(!that.img_preview_box_el){
                let previewHtml=`<div class="img-preview-box">
                                        <img src="${src}" alt="" title="点击预览">
                                        <i class="layui-icon layui-icon-delete img-delete-btn" title="${that.args.disabled?'禁用':'删除'}"></i>
                                    </div>`;
                that.fieldBoxEl.find('.img-upload-box').prepend(previewHtml);
                that.img_preview_box_el=that.fieldBoxEl.find('.img-upload-box .img-preview-box');
            }
        }

        // 设置上传进度数据
        set_upload_progress_data(args={}){
            let defArgs={
                rate_num:0
            };
            args=yunj.objSupp(args,defArgs);
            let that=this;
            that.upload_progress_rate_num=args.rate_num;

            if(that.img_preview_box_el.find('.layui-progress').length<=0){
                let progressHtml=`<div class="layui-progress layui-progress-big">
                                      <div class="layui-progress-bar" style="width:0%;">
                                        <span class="layui-progress-text">0%</span>
                                      </div>
                                  </div>`;
                that.img_preview_box_el.append(progressHtml);
            }

            let percent=args.rate_num+'%';
            that.img_preview_box_el.find('.layui-progress-bar').css({'width':percent});
            that.img_preview_box_el.find('.layui-progress-text').html(percent);
        }

        // 上传开始
        upload_progress_start(){
            let that=this;

            that.set_upload_progress_data({
                rate_num:0,
            });
            that.upload_progress_timer=setInterval(function () {
                let rateNum=that.upload_progress_rate_num;
                rateNum = rateNum + Math.random()*10|0;
                rateNum = rateNum>99?99:rateNum;

                that.set_upload_progress_data({
                    rate_num:rateNum,
                });
            },300+Math.random()*1000);
        }

        // 上传结束
        upload_progress_end(data){
            let that=this;

            clearInterval(that.upload_progress_timer);

            that.set_upload_progress_data({
                rate_num:100,
            });
            that.img_preview_box_el.find('img').attr('src',data.url);
            that.img_preview_box_el.find('img').attr('alt',data.fileName);
            setTimeout(function () {
                that.delete_upload_item_data();
            },1000);
        }

        // 上传错误
        upload_error(tips=''){
            let that=this;
            if(tips.length<=0){
                that.img_preview_box_el.find('.img-upload-error-tips').remove();
                return false;
            }
            let html=`<div class="img-upload-error-tips">${tips}</div>`;
            that.img_preview_box_el.append(html);
            that.delete_upload_item_data();
        }

        // 删除上传数据
        delete_upload_item_data(){
            let that=this;
            if(that.upload_progress_timer){
                clearInterval(that.upload_progress_timer);
                that.upload_progress_timer=null;
            }
            that.img_preview_box_el.find('.layui-progress').hide();
        }

        // 设置上传事件绑定
        set_upload_event_bind(){
            let that = this;
            let args={
                elem:`#${that.id} .img-select-box`,
                url:'/file/upload.html?from=input',
                accept:'image',
                acceptMime:that.args.ext.split(',').map(item=>{return `image/${item}`;}).join(','),
                exts:that.args.ext.replace(/,/g,'|'),
                auto:false,
                bindAction:that.upload_action_elem,
                field:'file',
                size:that.args.size*1024,
                number:1,
                drag:false,
                choose:function (obj) {
                    if(!yunj.isObj(that.upload_files)||!yunj.isEmptyObj(that.upload_files)){
                        yunj.msg('待上传完成后，执行此操作');
                        return false;
                    }
                    that.upload_files=obj.pushFile();

                    async function setAddImgPreview() {
                        let src='';
                        let i=0;
                        for(let index in that.upload_files){
                            if(!that.upload_files.hasOwnProperty(index)) continue;
                            if(i>0) delete that.upload_files[index];
                            await new Promise((resolve, reject)=>{
                                let file=that.upload_files[index];
                                let reader = new FileReader();
                                reader.readAsDataURL(file);
                                reader.onload = function(){
                                    resolve(this.result);
                                }
                            }).then(img_src=>{src=img_src});
                        }

                        that.set_img_preview_box_layout(src);

                        that.upload_progress_start();
                        return true;
                    }
                    setAddImgPreview().then(res=>{$(that.upload_action_elem).click();});
                },
                done:function (res, index, upload) {
                    delete that.upload_files[index];
                    if(res.errcode!==0){
                        that.upload_error(res.msg);
                        return false;
                    }
                    that.upload_progress_end(res.data);
                }
            };

            upload.render(args);
        }

        defineExtraEventBind(){
            let that=this;

            if(!that.args.disabled){
                // 上传
                that.set_upload_event_bind();

                // 删除
                that.fieldBoxEl.on('click','.img-preview-box .img-delete-btn', function (e) {
                    that.setValue();
                    e.stopPropagation();
                });
            }

            // 预览
            that.fieldBoxEl.on('click','.img-preview-box img', function (e) {
                let src=that.getValue();
                if(src.length<=0) return false;
                yunj.previewImg(src);
            });
        }
    }

    exports('field_img', YunjImg);
});